const moment = require("moment");
const db = require("../models");
const logger = require("../utils/utils.logger").logger();
const DAO = require("../dao/DAO");
// lostPropertyOrder 失物数据表 lostOrder失物订单
const LostAndFind = db.lostAndFind;

// 创建一个新的失物招领单
exports.create = async (req, res) => {
  const pm = req.body;
  // 请求验证
  if (!pm.uid)
    return res.sendResult({ data: "", code: 605, message: "用户ID不能为空！" });
  if (!pm.propertyPicture)
    return res.sendResult({
      data: "",
      code: 605,
      message: "物品图片不能为空！",
    });
  if (!pm.describe)
    return res.sendResult({
      data: "",
      code: 605,
      message: "物品描述不能为空！",
    });
  // Create a lostPropertyOrder
  const tag = pm.lostOrderType === "0" ? "LOST" : "FIND";
  const data = {
    lostOrFindOrderId: `${tag}${moment().format("YYYYMMDDHHmmss")}`,
    uid: pm.uid,
    lostOrFindAddress: pm.lostOrFindAddress,
    phone: pm.phone,
    targetAddress: pm.targetAddress,
    remark: pm.remark,
    describe: pm.describe,
    lostOrFindTime: pm.lostOrFindTime,
    lostOrderType: pm.lostOrderType,
    propertyPicture: pm.propertyPicture,
  };

  DAO.create(LostAndFind, data, async (result) => {
    logger.debug(
      `${req.method} ${req.baseUrl + req.path} *** 参数：${JSON.stringify(
        pm
      )}; 响应：${JSON.stringify(result)}`
    );

    res.sendResult(result);
  });
};

// 查询所有的失物招领信息
exports.findAll = (req, res) => {
  const pm = {
    sort: {
      prop: "createdAt",
      order: "desc",
    },
  };
  DAO.list(LostAndFind, pm, (list) => {
    logger.debug(
      `${req.method} ${req.baseUrl + req.path} *** 参数：${JSON.stringify(
        pm
      )}; 响应：${JSON.stringify(list)}`
    );
    res.sendResult(list);
  });
};

// 取消失物招领信息
exports.cancelLostOrder = (req, res) => {
  const pm = req.query;
  // 请求验证
  if (!pm.lostOrFindOrderId)
    return res.sendResult({
      data: "",
      code: 605,
      message: "失物招领ID不能为空！",
    });

  DAO.delete(
    LostAndFind,
    { lostOrFindOrderId: pm.lostOrFindOrderId },
    async (updateResult) => {
      res.sendResult(updateResult);
    }
  );
};
